package 力扣.链表.双指针;


public class 重排链表143 {
    public void reorderList(ListNode head) {
        ListNode dummy = new ListNode();
        dummy.next = head;
         ListNode fast = dummy;
         ListNode slow = dummy;
         //取中间节点
         while (fast != null){
             if (fast.next != null){
                 fast = fast.next.next;
                 slow = slow.next;
             }else {
                 slow = slow.next;
                 break;
             }
         }
         if (slow == null){//传入空链表
             return;
         }
//       对链表后半部分进行反转
         ListNode mid = slow.next;
         slow.next = null;
         ListNode pre = null;
         while (mid != null){
             ListNode t2 = mid.next;
             mid.next = pre;

             pre = mid;
             mid = t2;
         }
         //对前半部分进行插入
         ListNode ans = dummy.next;
         while (pre != null){
             ListNode te = pre;
             pre = pre.next;

             ListNode ans2 = ans.next;
             te.next = ans.next;
             ans.next = te;
             ans = ans2;

         }
         head =  dummy.next;
    }

    public static void reorderList2(ListNode head) {
        if (head == null){
            return;
        }
         ListNode slow = head;
         ListNode fast = head;
         while(fast != null && fast.next != null){//取中间节点（快慢指针）
             fast = fast.next.next;
             slow = slow.next;
         }
         ListNode mid = slow.next;
         //反转链表
        ListNode pre = null;
        ListNode t1 = mid;
        while (t1 != null){
            ListNode t2 = t1.next;
            t1.next = pre;
            pre = t1;
            t1 = t2;
        }
        //置空
        slow.next = null;
        //插入
        ListNode p = head;
        while (pre != null){
            ListNode p1 = p.next;
            ListNode pre2 = pre.next;
            pre.next = p.next;
            p.next = pre;
            p = p1;
            pre = pre2;
        }
    }
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);


        reorderList2(head);

    }



}
